import asyncio
import json

from autobahn.asyncio import WebSocketClientFactory, WebSocketClientProtocol

from Lib import Utils


class MessageEvent:
    def __init__(self, data, header=None):
        if header is None:
            header = {}
        self.header = {**{}, **header}
        self.data = data
        self.send_time = Utils.NowTime()

    def ToJson(self):
        return {
                "header"   : self.header,
                "send_time": self.send_time,
                "data"     : self.data
        }

    def ToString(self):
        return json.dumps(self.ToJson()).encode("utf-8")


class MyClientProtocol(WebSocketClientProtocol):
    def onOpen(self):
        global user_data
        self.sendMessage(MessageEvent({"user_name": "测试账号", "user_id": 10086}, {"proto": "user_login"}).ToString())

    def onMessage(self, payload: bytes, isBinary: bool):
        global user_data, udp_port
        payload = json.loads(payload.decode("utf-8"))
        print(payload)
        header = payload['header']
        data = payload['data']
        send_time = payload['send_time']
        proto = header['proto']


class TcpClient:
    def __init__(self, loop):
        self.loop = loop
        asyncio.set_event_loop(loop)
        factory = WebSocketClientFactory()
        factory.protocol = MyClientProtocol
        loop.create_task(loop.create_connection(factory, '127.0.0.1', 6789))
        loop.run_forever()

